//
//  recordMenu.m
//  SoundPill
//
//  Created by 宋旭东 on 15/7/24.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "recordMenu.h"
#import "recordMenuItem.h"
#import "recordMenuButton.h"
#import "AppDelegate.h"
#import "RecordViewController.h"
#import "AFNetworking.h"
#import "UIViewExt.h"
#import "JCAlertView.h"
@interface recordMenu ()<UITableViewDataSource,UITableViewDelegate, UIScrollViewDelegate,UITextViewDelegate,UITextFieldDelegate>
{
    NSInteger pages;
    NSInteger page;
    BOOL isTopic;
}
@property (strong, nonatomic) NSMutableArray *button_;
@property (strong, nonatomic) NSMutableArray *topicArray;
@property (strong, nonatomic) UITableView *tableview;
//@property (strong, nonatomic) UIButton *disMissButton;
@property (strong, nonatomic) UIButton *backBtn;
@property (strong, nonatomic) recordMenuButton *changeBtn;
@property (strong, nonatomic) recordMenuButton *createTopic;
@property (strong, nonatomic) UIView *changJingView;


@property (strong, nonatomic) NSMutableArray *changJingArray;
@end


@implementation recordMenu
- (instancetype)initWithFrame:(CGRect)frame Content:(NSArray *)content
{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
//        self.disMissButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        _disMissButton.frame = CGRectMake(0, 0, self.bounds.size.width * 2, self.bounds.size.height);
//        [_disMissButton addTarget:self action:@selector(disMiss:) forControlEvents:UIControlEventTouchUpInside];
//        [self addSubview:_disMissButton];
        self.content = [NSArray arrayWithArray:content];
        self.button_ = [[NSMutableArray alloc] init];
        self.changJingArray = [NSMutableArray arrayWithObjects:@"音 乐",@"记 录",@"读 书",@"电 影",@"谈 话", @"故 事",@"旅 行",@"段 子",@"买 卖",@"教 学",@"其 他",
                                nil];
//        [self AFNetworking:1];
        [self createItem];
//        [self createTopicTableView];
//        [self createChangJingView];
//        [self create_TopicView];
    }
    return self;
}
- (void)createItem {
//    itemFrameX = 0.0;
    for (int i = 0; i < _content.count; i++) {
            recordMenuItem *item = [[recordMenuItem alloc] initWithFrame:CGRectMake(self.center.x - self.frame.size.width / 3 + (self.frame.size.width / 3 * (i % 3)), self.frame.size.height, self.frame.size.width / 3, self.frame.size.width / 3 + 20) isScene:NO];
            NSString *imageName = [NSString stringWithFormat:@"%@1.png",_content[i]];
            item.contentImage.image = [UIImage imageNamed:imageName];
            item.contentTitle.text = _content[i];
            [self addSubview:item];
            [_button_ addObject:item];
            if (i ==  2 ) {
//                item.maskLable.hidden = YES;
                [item setMaskLableHidden:YES];
//                item.contentTitle.hidden = NO;
                [item addTarget:self action:@selector(showChangJing:) forControlEvents:UIControlEventTouchUpInside];
            }  else {
//                item.maskLable.hidden = NO;
//                item.contentTitle.hidden = YES;
                [item setMaskLableHidden:NO];
                [item addTarget:self action:@selector(presentToRecord:) forControlEvents:UIControlEventTouchUpInside];
            }
    }
}

- (void)ChangeItemFrame {
    for (int i = 0; i < _button_.count; i++) {
        if (i <= 8) {
            recordMenuItem *item = (recordMenuItem *)_button_[i];
            [UIView animateWithDuration:0.25 animations:^{
                item.frame = CGRectMake(self.center.x - self.frame.size.width / 3 + (self.frame.size.width / 3 * (i % 3)), (self.frame.size.height - item.frame.size.height - 40  + (self.frame.size.width / 3 ) * (i / 3)), self.frame.size.width / 3, self.frame.size.width / 3 );
            } completion:^(BOOL finished) {
//                item.frame = CGRectMake((self.frame.size.width / 3 * (i % 3)), (self.frame.size.height - item.frame.size.height - 40  + (self.frame.size.width / 3 ) * (i / 3))-15, self.frame.size.width / 3, self.frame.size.width / 3 );
//                _tableview.center = CGPointMake(self.center.x, item.top / 2);
//                _changeBtn.center = CGPointMake(self.width / 4 + 10, item.top - 80);
//                _createTopic.center = CGPointMake(self.width / 4 * 3 - 10, item.top - 80);
//                _tableview.hidden = NO;
//                _changeBtn.hidden = NO;
//                _createTopic.hidden = NO;
                [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
//                    _tableview.alpha = 1.0;
//                    _changeBtn.alpha = 1.0;
//                    _createTopic.alpha = 1.0;
                } completion:^(BOOL finished) {
                    
                }];
                
            }];
            
        } else {
        recordMenuItem *item = (recordMenuItem *)_button_[i];
            [UIView animateWithDuration:0.3 animations:^{
                item.frame = CGRectMake(self.frame.size.width + (self.frame.size.width / 3 * (i % 3)), (self.frame.size.height / 2 - (self.frame.size.width / 3 + 40)) + (self.frame.size.width / 3 + 40) * ((i - 6) / 3), self.frame.size.width / 3, self.frame.size.width / 3 + 40);
            } completion:^(BOOL finished) {
                
            }];
        }
    }
}
- (void)create_TopicView
{
    
    
    
    
    
    
    
}
- (void)createChangJingView
{
    self.changJingView = [[UIView alloc] initWithFrame:CGRectMake(20, 60, self.frame.size.width - 40, self.height * 0.6)];
    if ([UIScreen mainScreen].bounds.size.height > 667) {
        _changJingView.frame = CGRectMake(20, 60, self.frame.size.width - 40, 400);
    }
//    _changJingView.backgroundColor = [UIColor redColor];
    [self addSubview:_changJingView];
    for (int i = 0; i < _changJingArray.count; i++) {
            recordMenuItem *item = [[recordMenuItem alloc] initWithFrame:CGRectMake((_changJingView.width / 2 * (i % 2)), _changJingView.height / 6 * (i / 2), self.width / 2, self.width / 6) isScene:YES];
            NSString *imageName = [NSString stringWithFormat:@"%@_scene.png",_changJingArray[i]];
            item.contentImage.image = [UIImage imageNamed:imageName];
            item.contentTitle.text = _changJingArray[i];
            [_changJingView addSubview:item];
//            [_button_ addObject:item];
            [item addTarget:self action:@selector(changjingPresentToRecord:) forControlEvents:UIControlEventTouchUpInside];
        }
    _changJingView.hidden = YES;
    _changJingView.alpha = 0.0;
}
- (void)createTopicTableView {
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(self.frame.size.width, 0, self.frame.size.width, 45 * 5)];
    _tableview.backgroundColor = [UIColor clearColor];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.pagingEnabled = YES;
    _tableview.showsVerticalScrollIndicator = NO;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.separatorColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
//    _tableview.center = CGPointMake(self.center.x, item.top / 2);
    [self addSubview:_tableview];
    _tableview.hidden = YES;
    _tableview.alpha = 0.0;
    
    self.changeBtn = [[recordMenuButton alloc] initWithFrame:CGRectMake(10, 0, 140, 40) image:[UIImage imageNamed:@"menuTopicChange"] title:@"换一批"];
    _changeBtn.backgroundColor = [UIColor blackColor];
//    [_changeBtn setBackgroundImage:[UIImage imageNamed:@"menuTopicChange"] forState:UIControlStateNormal];
//    _changeBtn.frame = CGRectMake(0, 0, 30,30);
//    _changeBtn.center = CGPointMake([UIScreen mainScreen].bounds.size.width *1.5, [UIScreen mainScreen].bounds.size.height - (44 * 2.5));
    _changeBtn.hidden = YES;
    _changeBtn.alpha = 0.0;
    [_changeBtn addTarget:self action:@selector(changTopic) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_changeBtn];
    
    self.createTopic = [[recordMenuButton alloc] initWithFrame:CGRectMake(0, 0, 140, 40) image:[UIImage imageNamed:@"createTopic"] title:@"创建话题"];
//    [_createTopic setTitle:@"创建话题" forState: UIControlStateNormal];
//    _createTopic.frame = CGRectMake(0, 0, _tableview.width / 2, 40);
    _createTopic.backgroundColor =  [UIColor blackColor];
    [_createTopic setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_createTopic addTarget:self action:@selector(createTopicClick:) forControlEvents:UIControlEventTouchUpInside];
    _createTopic.hidden = YES;
    _createTopic.alpha = 0.0;
    [self addSubview:_createTopic];
}
- (void)createTopicClick:(UIButton *)sender
{
    if (_tableview.hidden == NO) {
        _tableview.hidden = YES;
        _tableview.alpha = 0.0;
        _changeBtn.hidden = YES;
        _createTopic.hidden = YES;
    }
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
    } completion:^(BOOL finished) {
        
    }];
}
- (void)cancelCreateTopic:(UIButton *)sender
{
    _tableview.hidden = NO;
    _changeBtn.hidden = NO;
    _createTopic.hidden = NO;
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        _tableview.alpha = 1.0;
        _changeBtn.alpha = 1.0;
        _createTopic.alpha = 1.0;
    } completion:^(BOOL finished) {
        
    }];
}
- (void)presentToRecord:(recordMenuItem *)sender
{
    NSString *str = [sender.contentTitle.text stringByReplacingOccurrencesOfString:@"（" withString:@""];
    str = [[str stringByReplacingOccurrencesOfString:@" " withString:@"#"] stringByReplacingOccurrencesOfString:@"）" withString:@""];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:1], @"isStart", str, @"tag", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"disMissMenu" object:dic];
}
- (void)changjingPresentToRecord:(recordMenuItem *)sender {
    [self presentToRecord:sender];
    [[NSUserDefaults standardUserDefaults] setObject:sender.contentTitle.text forKey:@"changjing"];
}

- (void)disMiss:(UIButton *)button
{
    NSString *str = button.currentTitle;
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:0], @"isStart", str, @"tag", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"disMissMenu" object:dic];
}
- (void)showChangJing:(recordMenuItem *)item
{
        if (![item.contentTitle.text isEqualToString:@"话 题"]) {
            item.contentImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@_select.png",item.contentTitle.text]];
            [self changeOtherButtonWithTitle:@"话 题"];
        isTopic = NO;
        if (_tableview.hidden == NO) {
            _tableview.hidden = YES;
            _tableview.alpha = 0.0;
            _changeBtn.hidden = YES;
        }
               [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        } completion:^(BOOL finished) {
            
        }];
    } else {
        item.contentImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@1.png",item.contentTitle.text]];
        [self changeOtherButtonWithTitle:@"发起话题"];
        
        _tableview.hidden = NO;
        _changeBtn.hidden = NO;
        [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            _tableview.alpha = 1.0;
            _changeBtn.alpha = 1.0;
        } completion:^(BOOL finished) {
            
        }];
        AppDelegate *delegate = [AppDelegate shareDelegate];
        delegate.startTag =  [item.contentTitle.text stringByReplacingOccurrencesOfString:@" " withString:@"#"];
    }
}
- (void)changeOtherButtonWithTitle:(NSString *)title
{
    for (int i = 0; i < _button_.count; i++) {
        recordMenuItem *unselectItem = (recordMenuItem *)_button_[i];
        if ([unselectItem.contentTitle.text isEqualToString:title]) {
            if ([title isEqualToString:@"话 题"]) {
                unselectItem.contentImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@_unSelect.png",unselectItem.contentTitle.text]];
            } else if ([title isEqualToString:@"发起话题"]){
                unselectItem.contentImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@1.png",unselectItem.contentTitle.text]];
            }
            
            break;
        }
    }
}
- (void)scrollToTopPage:(recordMenuItem *)sender
{
    [self setContentOffset:CGPointZero animated:NO];
    [AppDelegate shareDelegate].butt.hidden = NO;
}
- (void)changTopic{
    if (page < pages) {
        page++;
        [self AFNetworking:page];
    } else {
        [self AFNetworking:1];
    }
}
#pragma mark -
#pragma mark tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _topicArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier1 = @"topic";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier1];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    NSString *string = nil;
    if (isTopic == YES) {
        string = [NSString stringWithFormat:@"#%@#", _topicArray[indexPath.row]];
    } else {
        string = _topicArray[indexPath.row];
    }
    cell.textLabel.text = string;
    if ([UIScreen mainScreen].bounds.size.width == 320) {
        cell.textLabel.font = [UIFont boldSystemFontOfSize:16];
    } else {
        cell.textLabel.font = [UIFont boldSystemFontOfSize:20];
    }
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *str = _topicArray[indexPath.row];
    [AppDelegate shareDelegate].startTag = @"话#题";
    [AppDelegate shareDelegate].topicString = str;
    [[AppDelegate shareDelegate] disMisMenuBtnClick:nil];
    RecordViewController *record = [[RecordViewController alloc] initWithType:[AppDelegate shareDelegate].startTag detile:[AppDelegate shareDelegate].topicString];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:record];
    [[AppDelegate shareDelegate].window.rootViewController presentViewController:nav animated:YES completion:nil];
    
}
#pragma mark -
#pragma mark scrollview
//- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
//{
//
//}
//- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
//{
//    if (scrollView.contentOffset.x == self.frame.size.width) {
//        [UIView animateWithDuration:0.5 animations:^{
//            _backBtn.frame = CGRectMake(self.frame.size.width + 5, 20, 44, 44);
//        }];
//    }
//}


#pragma mark -
#pragma 网络请求
- (void)AFNetworking:(NSInteger)pag{
    //    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    page = pag;
    self.topicArray = [[NSMutableArray alloc] init];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/tag/topic?p=%ld",page];
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        //        if (isTopic == YES) {
        NSDictionary *dict = [dic valueForKey:@"data"];
        for (NSDictionary *dicti in dict) {
            [_topicArray addObject:[dicti valueForKey:@"name"]];
        }
        pages = [[[dic valueForKey:@"meta"] valueForKey:@"pages"] integerValue];
        if (pages == 1) {
            _changeBtn.hidden = YES;
        }
        [_tableview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
